<?php
global $config;
require_once('BaseModel.class.php');
Class LoginModel extends BaseModel
{
    function authenticate_username($login, $password,$ipaddr )
    {
        $query = "SELECT auths.*,usertype.usertype_name as privilege,usertype.usertype_code as privilege_code FROM auths
		  LEFT JOIN usertype ON auths.privilege=usertype.id 
		  WHERE login='{$login}' AND auths.active='1'";
        $auth = $this->query($query, true);
        if($auth){
            if($auth[0]['password'] == md5($password)){
                $auth = Array('id' => $auth[0]['id'],
                              'fullname' => $auth[0]['lastname'] . ", " . $auth[0]['firstname'],
                              'username' => $auth[0]['login'],
                              'privilege' => $auth[0]['privilege'],
                              'privilege_level' => $auth[0]['privilege_level'],
                              'privilege_code' => $auth[0]['privilege_code'],
                              'Ipaddr' => $auth[0]['Ipaddress']);          
                $this->update('auths', array('online' => '1','Ipaddress'=> $ipaddr),'id=' . $auth['id']);
                return $auth;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
  function insert_ipaddr($ip_address,$username,$is_user)
  {
    if($is_user){
      $this->update('auth',array('ipaddress' => $ip_address,'available' => 'Y'), "user_name = '$username'");
    }else{
      $this->update('auth',array('ipaddress' => $ip_address), "user_name = '$username'");
    }
  }

    function logout($uid)
    {
        return $this->update('auths', array('online' => '0'), 'id="' . $uid. '"');
    }

    function get_auths()
    {
        $query = "SELECT `id`, `login`, `online` FROM `auths` WHERE `active`='1'";
        return $this->query($query, true);
    }

    function get_online_auths()
    {
        $query = "SELECT auths.`id`, `login`, `online`,usertype.`usertype_name` as privilege,Ipaddress FROM `auths` LEFT JOIN usertype ON auths.privilege = usertype.id WHERE `online`='1'";
        return $this->query($query, true);
    }

    function get_user_email($uid)
    {
        $query = "SELECT `email` FROM `auths` WHERE `id`={$uid}";
        return $this->query($query, true);
    }

    function check_online_users()
    {
        $query = "SELECT COUNT(*) FROM `auths` WHERE `online`='1'";
        return $this->query($query, true);
    }
}
?>
